<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>水库管理系统 - 水库列表</title>
    <link rel="stylesheet" href="CSS/style.css">
    <link rel="stylesheet" href="CSS/apple-style.css">
</head>
<body>
<div class="container">
    <div class="header">
        <h2>水库管理系统</h2>
        <div class="user-info">
            <span id="welcome-message">欢迎回来，用户</span>
            <a href="LogoutServlet" class="btn">登出系统</a>
        </div>
    </div>

    <div class="content">
        <div class="actions">
            <button id="add-dam" class="btn">新建水库</button>
        </div>

        <div class="search-bar">
            <input type="text" id="search-name" placeholder="按水库名搜索">
            <input type="text" id="search-river" placeholder="按所属河流搜索">
            <button id="search-btn" class="btn">搜索</button>
        </div>

        <table id="dam-table">
            <thead>
            <tr>
                <th>水库名</th>
                <th>所属河流</th>
                <th>库容（亿立方米）</th>
                <th>建成时间</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <!-- 数据将通过JavaScript动态加载 -->
            </tbody>
        </table>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 从服务器获取用户信息并显示欢迎信息
        getSessionUser().then(user => {
            if (user) {
                document.getElementById('welcome-message').textContent = '欢迎回来，用户 ' + user.username;
            }
        });

        // 加载水库列表
        loadDams();

        // 搜索结果按钮点击事件
        document.getElementById('search-btn').addEventListener('click', loadDams);

        // 输入框回车事件
        document.getElementById('search-name').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') loadDams();
        });

        document.getElementById('search-river').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') loadDams();
        });

        // 新建水库按钮点击事件
        document.getElementById('add-dam').addEventListener('click', function() {
            window.location.href = 'addDam.html';
        });

        // 加载水库列表函数
        function loadDams() {
            const name = document.getElementById('search-name').value;
            const river = document.getElementById('search-river').value;

            fetch(`GetUDamListServlet?name=${encodeURIComponent(name)}&river=${encodeURIComponent(river)}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络请求失败');
                    }
                    return response.json();
                })
                .then(dams => {
                    const tbody = document.querySelector('#dam-table tbody');
                    tbody.innerHTML = '';

                    if (dams.length === 0) {
                        const row = document.createElement('tr');
                        row.innerHTML = '<td colspan="5" style="text-align: center;">没有找到相关水库</td>';
                        tbody.appendChild(row);
                        return;
                    }

                    dams.forEach(dam => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${dam.name}</td>
                            <td>${dam.river}</td>
                            <td>${dam.capacity}</td>
                            <td>${dam.completeDate}</td>
                            <td>
                                <a href="updateDam.html?id=${dam.id}">修改</a>
                                <a href="javascript:void(0)" data-id="${dam.id}" class="delete-dam">删除</a>
                            </td>
                        `;
                        tbody.appendChild(row);
                    });

                    // 删除按钮点击事件
                    document.querySelectorAll('.delete-dam').forEach(link => {
                        link.addEventListener('click', function() {
                            if (confirm('确定要删除该水库吗？')) {
                                const id = this.getAttribute('data-id');
                                deleteDam(id);
                            }
                        });
                    });
                })
                .catch(error => {
                    console.error('加载水库列表失败:', error);
                    alert('加载水库列表失败，请检查网络连接或服务器状态！');
                });
        }

        // 删除水库函数
        function deleteDam(id) {
            fetch(`DeleteDamServlet?id=${id}`, {
                method: 'DELETE'
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('删除失败');
                    }
                    return response.json();
                })
                .then(result => {
                    if (result.success) {
                        alert('删除成功！');
                        loadDams();
                    } else {
                        alert('删除失败！');
                    }
                })
                .catch(error => {
                    console.error('删除水库失败:', error);
                    alert('删除水库失败，请检查网络连接或服务器状态！');
                });
        }

        // 从服务器获取用户信息
        async function getSessionUser() {
            try {
                const response = await fetch('GetUserServlet');
                if (!response.ok) {
                    return null;
                }
                return await response.json();
            } catch (error) {
                console.error('获取用户信息失败:', error);
                return null;
            }
        }
    });
</script>
</body>
</html>